/*
 * 文 件 名:  BaseController.java
 * 版    权:  kuanrf  Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  sheng.li
 * 修改时间:  2015年4月15日
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.showcai.controller.base;

import com.google.gson.reflect.TypeToken;
import com.showcai.def.Constant;
import com.showcai.log.LogFactory;
import com.showcai.module.AdminUser;
import com.showcai.module.User;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.result.ReturnCode;
import com.showcai.service.UserService;
import com.showcai.service.UserThirdService;
import com.showcai.tools.aliUpload.AliUploadTools;
import com.showcai.tools.json.JsonHandler;
import com.showcai.util.FileTools;
import com.showcai.util.MD5Tools;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author sheng.li
 * @version [版本号, 2015年4月15日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public abstract class BaseController {
    protected Logger logger = LogFactory.getLogger(getClass());

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpSession session;
    @Autowired
    protected UserThirdService userThirdService;

    @Autowired
    protected UserService userService;

    private static final String PASSWORD = "123456";

    protected void modifySession() {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
        user = userService.getUserById(user.getTid());
        session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
    }

    protected User getUserBySession() {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_KEY_USER_LOGIN);
        return user;
    }

    protected AdminUser getAdminUserBySession() {
        HttpSession session = request.getSession();
        AdminUser adminUser = (AdminUser) session.getAttribute(Constant.SESSION_KEY_ADMIN_USER_LOGIN);
        return adminUser;
    }

    protected Map<String, String> showRequestParameters() {
        Enumeration<?> paramNames = request.getParameterNames();
        logger.info("showRequestParameters=============================================>>>>>>" + paramNames.hasMoreElements());
        Map<String, String> map = new HashMap<String, String>();
        while (paramNames.hasMoreElements()) {

            String paramName = paramNames.nextElement().toString();
            String paramValue = request.getParameter(paramName);
            map.put(paramName, paramValue);
            logger.info(paramName + "[:]" + paramValue);
        }

        try {
            User user = (User) request.getSession().getAttribute(Constant.SESSION_KEY_USER_LOGIN);
            if (user != null) {
                map.put("userId", String.valueOf(user.getTid()));
            }

        } catch (Exception e) {
            logger.info(e.getMessage());
        }


        return map;
    }

    protected String upLoadFile(InputStream inputStream, String filePath) throws Exception {
        filePath += FileTools.getUniquenessName("") + FileTools.PICTURE_SUFFIX_JPG;

        AliUploadTools.AliUploadInputStream(inputStream, true, filePath);
        filePath = AliUploadTools.PICURLADDRESS + filePath;
        return filePath;
    }


    protected String putObject(InputStream inputStream, String filePath, String fileName) {
        logger.info("fileName =====================>>>>" + fileName);
        String fileTypes[] = fileName.split("\\.");
        logger.info("fileTypes =====================>>>>" + fileTypes.length);
        for (int i = 0; i < fileTypes.length; i++) {
            logger.info("fileTypes[" + i + "]===>>" + fileTypes[i]);
        }
        fileName = FileTools.getUniquenessName("") + "." + fileTypes[fileTypes.length - 1];


        AliUploadTools.putObject(inputStream, fileTypes[fileTypes.length - 1], filePath + fileName);
        filePath = AliUploadTools.PICURLADDRESS + filePath + fileName;
        return filePath;
    }

    protected User checkUser(String phone, String name) {
        User user = userService.getUserByPhone(phone);
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setNickName(name);
            user.setCreateTime(new Date());
            user.setPassWord(MD5Tools.MD5(PASSWORD));
            user.setStatus(User.STATUS_VALID);
            user = userService.addUser(user);
        }
        session.setAttribute(Constant.SESSION_KEY_USER_LOGIN, user);
        return user;
    }

    protected Object json2Obj(Type clazz) {
        String str, wholeStr = "";
        try {
            BufferedReader br = request.getReader();

            while ((str = br.readLine()) != null) {
                wholeStr += str;
            }
            logger.info(wholeStr);
        } catch (IOException e) {
            throw new MyRunTimeExcption(ReturnCode.NET_ERRO);
        }
        return JsonHandler.json2Obj(wholeStr, clazz);
    }

    protected <T> T json2List(TypeToken<T> t) {
        logger.info("sync User============================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        String str, wholeStr = "";
        try {
            BufferedReader br = request.getReader();

            while ((str = br.readLine()) != null) {
                wholeStr += str;
            }
            System.out.println("===========================>>>>>>>>>>>>>>>>>>>>>wholeStr>>>>>>>>>>>>>>>>>>>>>>>");
            System.out.println(wholeStr);
            System.out.println("===========================>>>>>>>>>>>>>>>>>>>>>wholeStr>>>>>>>>>>>>>>>>>>>>>>>");
        } catch (IOException e) {
            throw new MyRunTimeExcption(ReturnCode.NET_ERRO);
        }
        return JsonHandler.json2ObjList(wholeStr, t);
    }

}
